package com.yricky.memoria.data

import com.google.gson.annotations.Expose
import com.yricky.memoria.data.pojo.SectionQuery
import com.yricky.memoria.utils.gson
import java.io.File

/**
 * @author Yricky
 * @date 2021/11/21
 */
class Section(
    val model: SubjectModel,
    private val dir: File,
    var metaData: SubjectModel.SectionMetaData
    ) {
    init {
        if(!dir.exists()){
            dir.mkdirs()
        }
    }

    val uid get() = dir.name
    val assetsDir get() = File(dir,"assets").also {
        if(!it.exists())
            it.mkdirs()
    }

    val jsonData:JsonData by lazy {
        try {
            gson.fromJson(File(dir,"data.json").readText(),JsonData::class.java)
        }catch (e:Throwable){
            JsonData().also {
                File(dir,"data.json").writeText(gson.toJson(it))
            }
        }
    }

    fun save(){
        File(dir,"data.json").writeText(gson.toJson(jsonData))
    }

    class JsonData{
        @Expose
        var items:List<Item> = ArrayList()
    }

    class Item(
        @Expose
        var type:String = "text",
        @Expose
        var content:String = "",
        @Expose
        val data:HashMap<String,String> = HashMap()
    ){
        companion object{
            const val TYPE_SECTION = "section"
            const val TYPE_TEXT = "text"
            const val TYPE_IMG = "img"
            const val TYPE_PDF = "pdf"
        }
    }
    companion object{
        val EmptyTextItem:Item get() = Item().apply {
            type = Item.TYPE_TEXT
        }

        fun imageItem(assetName:String):Item = let{
            Item().also {
                it.type = Item.TYPE_IMG
                it.content = assetName
            }
        }
    }
}